package cn.shanke.torrentmanagerserver.service;

import cn.shanke.torrentmanagerserver.config.AppConfig;
import cn.shanke.torrentmanagerserver.dao.ConfigMapper;
import cn.shanke.torrentmanagerserver.model.Config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
@Transactional
public class ConfigService extends ServiceImpl<ConfigMapper, Config> {
    @Resource
    private AppConfig appConfig;

    private volatile static Config current;
    public Config getCurrent() {
        if (current == null) {
            synchronized(ConfigService.class) {
                if (current == null) {
                    current = getOne(new QueryWrapper<Config>().lambda().eq(Config::getTag, "system"));
                    current.setManagePath(appConfig.getManagePath());
                }
            }
        }
        return current;
    }

    /**
     * 真实目录转为docker中的目录
     * @param src
     * @return
     */
    public String toVisualPath(String src) {
        if (appConfig.isDocker()) return src;
//        System.out.println("toVisualPath before:" + src);
        Config config = getCurrent();
        if (!StringUtils.hasText(src) && !StringUtils.hasText(config.getManagePathHost())) {
            src = src.replace(config.getManagePathHost(), config.getManagePath()).replace("\\\\", "/").replace("\\", "/");
        }
//        System.out.println("toVisualPath after:" + src);
        return src;
    }

    /**
     * docker中的目录转为真实目录
     * @param src
     * @return
     */
    public String toRealPath(String src) {
        if (appConfig.isDocker()) return src;
//        System.out.println("toRealPath before:" + src);
        Config config = getCurrent();
        if (!StringUtils.hasText(src) && !StringUtils.hasText(config.getManagePathHost())) {
            src = src.replace(config.getManagePath(), config.getManagePathHost());
            if (System.getProperty("os.name").toLowerCase().indexOf("windows")>=0) {
                src = src.replace("/", "\\");
            }
        }
//        System.out.println("toRealPath after:" + src);
        return src;
    }
}
